import { build } from 'vite'
import { visualizer } from 'rollup-plugin-visualizer'
import { resolve } from 'path'

async function analyzeBundles() {
  console.log('🔍 Starting bundle analysis...')
  
  try {
    await build({
      configFile: resolve(process.cwd(), 'apps/web/vite.config.ts'),
      root: resolve(process.cwd(), 'apps/web'),
      plugins: [
        visualizer({
          filename: 'dist/bundle-analysis.html',
          open: true,
          gzipSize: true,
          brotliSize: true,
          template: 'treemap' // Options: treemap, sunburst, network
        })
      ],
      build: {
        outDir: 'dist',
        sourcemap: true,
        rollupOptions: {
          output: {
            manualChunks: {
              // Vendor chunks
              vendor: ['react', 'react-dom'],
              'vendor-router': ['react-router-dom'],
              'vendor-ui': ['lucide-react', '@radix-ui/react-slot'],
              'vendor-i18n': ['react-i18next', 'i18next'],
              'vendor-forms': ['@rjsf/core', '@rjsf/validator-ajv8'],
              
              // Plugin system chunks
              'plugin-host': ['@bai-hu/plugin-host-web'],
              'plugin-sdk': ['@bai-hu/plugin-sdk'],
              'plugin-types': ['@bai-hu/plugin-registry-types'],
              
              // Feature chunks
              'pages-admin': [
                './src/pages/AdminPanel.tsx',
                './src/pages/AuditPage.tsx'
              ],
              'pages-plugins': [
                './src/pages/PluginManagement.tsx',
                './src/pages/PluginDetail.tsx'
              ],
              
              // Utility chunks
              'utils': [
                './src/utils/apiClient.ts',
                './src/utils/errorHandler.ts',
                './src/utils/performance.ts',
                './src/utils/serviceWorker.ts',
                './src/utils/dynamicImport.ts'
              ]
            },
            
            // Optimize chunk naming
            chunkFileNames: (chunkInfo) => {
              const facadeModuleId = chunkInfo.facadeModuleId
              if (facadeModuleId) {
                const name = facadeModuleId.split('/').pop()?.replace('.tsx', '').replace('.ts', '')
                return `chunks/${name}-[hash].js`
              }
              return 'chunks/[name]-[hash].js'
            },
            
            // Optimize asset naming
            assetFileNames: (assetInfo) => {
              const info = assetInfo.name.split('.')
              const ext = info[info.length - 1]
              if (/png|jpe?g|svg|gif|tiff|bmp|ico/i.test(ext)) {
                return `assets/images/[name]-[hash][extname]`
              }
              if (/woff2?|eot|ttf|otf/i.test(ext)) {
                return `assets/fonts/[name]-[hash][extname]`
              }
              return `assets/[name]-[hash][extname]`
            }
          }
        },
        
        // Optimize build settings
        target: 'esnext',
        minify: 'terser',
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true
          }
        },
        
        // Chunk size warnings
        chunkSizeWarningLimit: 1000
      }
    })
    
    console.log('✅ Bundle analysis complete!')
    console.log('📊 Open dist/bundle-analysis.html to view the analysis')
    
    // Generate bundle report
    await generateBundleReport()
    
  } catch (error) {
    console.error('❌ Bundle analysis failed:', error)
    process.exit(1)
  }
}

async function generateBundleReport() {
  console.log('📝 Generating bundle report...')
  
  const fs = await import('fs/promises')
  const path = await import('path')
  
  const distPath = resolve(process.cwd(), 'apps/web/dist')
  
  try {
    const files = await fs.readdir(distPath, { recursive: true })
    const stats = await Promise.all(
      files.map(async (file) => {
        const filePath = path.join(distPath, file)
        const stat = await fs.stat(filePath)
        if (stat.isFile()) {
          return {
            name: file,
            size: stat.size,
            sizeKB: Math.round(stat.size / 1024 * 100) / 100,
            type: path.extname(file)
          }
        }
        return null
      })
    )
    
    const fileStats = stats.filter(Boolean).sort((a, b) => b.size - a.size)
    
    const report = {
      timestamp: new Date().toISOString(),
      totalFiles: fileStats.length,
      totalSize: fileStats.reduce((sum, file) => sum + file.size, 0),
      totalSizeKB: Math.round(fileStats.reduce((sum, file) => sum + file.size, 0) / 1024 * 100) / 100,
      files: fileStats,
      breakdown: {
        js: fileStats.filter(f => f.type === '.js'),
        css: fileStats.filter(f => f.type === '.css'),
        images: fileStats.filter(f => /\.(png|jpg|jpeg|gif|svg|ico)$/.test(f.type)),
        fonts: fileStats.filter(f => /\.(woff|woff2|eot|ttf|otf)$/.test(f.type)),
        other: fileStats.filter(f => !['.js', '.css'].includes(f.type) && 
                                    !/\.(png|jpg|jpeg|gif|svg|ico|woff|woff2|eot|ttf|otf)$/.test(f.type))
      }
    }
    
    await fs.writeFile(
      path.join(distPath, 'bundle-report.json'),
      JSON.stringify(report, null, 2)
    )
    
    // Console summary
    console.log('\n📊 Bundle Summary:')
    console.log(`Total files: ${report.totalFiles}`)
    console.log(`Total size: ${report.totalSizeKB} KB`)
    console.log(`JavaScript: ${report.breakdown.js.length} files, ${Math.round(report.breakdown.js.reduce((sum, f) => sum + f.size, 0) / 1024 * 100) / 100} KB`)
    console.log(`CSS: ${report.breakdown.css.length} files, ${Math.round(report.breakdown.css.reduce((sum, f) => sum + f.size, 0) / 1024 * 100) / 100} KB`)
    console.log(`Images: ${report.breakdown.images.length} files, ${Math.round(report.breakdown.images.reduce((sum, f) => sum + f.size, 0) / 1024 * 100) / 100} KB`)
    
    console.log('\n🔝 Largest files:')
    fileStats.slice(0, 10).forEach(file => {
      console.log(`  ${file.name}: ${file.sizeKB} KB`)
    })
    
    console.log('\n✅ Bundle report saved to dist/bundle-report.json')
    
  } catch (error) {
    console.error('❌ Failed to generate bundle report:', error)
  }
}

// Run analysis
analyzeBundles()
